from rest_framework import serializers
from apps.users.models import User
from django.contrib.auth.models import Group
from django.db import transaction
class ManagerSerializer(serializers.ModelSerializer):
    class Meta:
        model= User
        # fields=['id','username','password','mobile','email','groups']
        fields='__all__'
        extra_kwargs={
            'password':{'write_only':True}
        }

    # def create(self, validated_data):
    #     groups=validated_data.pop('groups')
    #     with transaction.atomic():
    #         point=transaction.savepoint()
    #         instance=User.objects.create_user(**validated_data,is_staff=True)
    #         for group in groups:
    #             Group.objects.create(user=instance,group_id=group)
    #         transaction.savepoint_commit(point)
    #     return instance

    def create(self, validated_data):
        user=super().create(validated_data)
        user.is_staff=True
        user.set_password(validated_data.get('password'))
        user.save()
        return user

    def update(self, instance, validated_data):
        user=super().update(instance,validated_data)
        user.set_password(validated_data.get('password'))
        user.save()
        return user

